import { request } from '@/utils/request'

/**
 * 根据 md5 验证文件是否已上传
 */
function checkFileByMd5(md5) {
    return request({
        url: '/file/check',
        method: 'get',
        params: { md5 }
    })
}


/**
 * 上传文件分片
 * @param {*} fileName 文件名 
 * @param {*} md5  分片文件的md5
 * @param {*} chunkFile 分片文件
 * @param {*} index 分片索引
 * @param {*} chunkSize 分片大小
 * @returns 
 */
function uploadChunk(chunkFile, chunk) {
    const formData = new FormData();
    formData.append("file", chunkFile);
    formData.append("chunkIndex", chunk.index);
    formData.append("identifier", chunk.md5);
    formData.append("filename", chunk.fileName);
    formData.append("currentChunkSize", chunkFile.size);
    formData.append("type", chunkFile.type);
    formData.append("chunkSize", chunk.chunkSize);
    formData.append("totalSize", chunk.fileSize);
    formData.append("totalChunks", chunk.totalChunks);

    return request({
        url: '/chunk/upload',
        method: 'post',
        headers: {
            'content-type': 'multipart/form-data'
        },
        data: formData,
    })
}

/**
 * 检测分片是否存在
 * @param {*} identifier 
 * @param {*} filename 
 * @returns 
 */
function checkChunk(identifier, filename) {
    return request({
        url: '/chunk/check',
        method: 'get',
        params: { identifier, filename }
    })
}

function mergeChunks(params) {
    return request({
        url: '/chunk/merge',
        method: 'get',
        params,
    })
}

export {
    checkFileByMd5,
    uploadChunk,
    checkChunk,
    mergeChunks
}